$(document).ready(function () {


    layui.use(function () {

        var layer = layui.layer;

        layui.laydate.render({
            elem: "#input-date",
            range: true,
        });


        // 表格
        form = layui.form;
        form.on('select(type-select)', function (data) {
            $('div[lay-filter="search"]').click();
        });
        form.on('select(projectId-select)', function (data) {
            $('div[lay-filter="search"]').click();
        });


        form.on('select(person-select)', function (data) {
            $('div[lay-filter="search-record"]').click();
        });
        form.on('select(seq-select)', function (data) {
            $('div[lay-filter="search-record"]').click();
        });

        form.on('submit(search)', function (data) {//监听查询提交

            queryParams = data.field;

            if (queryParams.date != '') {
                queryParams.beginTime = queryParams.date.split(' - ')[0]
                queryParams.endTime = queryParams.date.split(' - ')[1]
            } else {
                queryParams.beginTime = ''
                queryParams.endTime = ''
            }
            queryParams.pageSize = 10;
            queryTable()
            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });



        form.on('submit(search-record)', function (data) {//监听历史查询
            gunHistoryParams = data.field;

            queryGunHistory()
            return false;
        });

        initSubMenu();

        $('.contain-tab')
            .empty()
            .append(
                new ST().project(1).reduce((x, y) => {
                    return x + `<div class="tab-item" data-type=${y.type}>${y.name}</div>`
                }, '')
            )
        // 顶部菜单切换
        $('.tab-item').click(function (e) {
            $(e.currentTarget).addClass('active').siblings().removeClass('active');

            var type = $(e.currentTarget).data().type;
            curType = type;
            new ST().trainProject(null, null, null, curType).then(data => {
                $('select[name="projectId"]').empty().append(data)
                form.render()

                $('div[lay-filter="search"]').click();

            })

        })
        $('.tab-item').eq(0).click()


    });
})
var queryParams = {};//查询条件参数
var form, unit;
var drawer;//抽屉实例
var curId = null;//当前选中ID
var curType = 1;



//查询列表
queryTable = () => {

    queryParams.trainType = curType;

    layui.use('table', function () {
        var table = layui.table;

        //展示已知数据
        table.render({
            elem: '#table'
            , text: {
                none: '暂无数据'
            }
            , method: 'get'
            , url: ajaxPrefix() + "/train/score/list"
            , headers: {
                SessionId: JSON.parse(localStorage.getItem('sessionId'))
            }
            , where: queryParams
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.result.total, //解析数据长度
                    "data": res.result.data //解析数据列表
                };
            }
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                ,
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , cols: [[ //标题栏
                { field: 'personName', title: '训练人', align: "center", hide: curType == 3 },
                { field: 'projectName', title: '训练项目', align: "center" },
                { field: 'helpPersonName', title: '扶梯人', align: "center", hide: curType != 6 },

                { field: 'useTime', title: '训练成绩（单位：秒）', align: "center" },
                {
                    field: 'trainResultDesc', title: '合格情况', align: "center"
                    , templet: function (d) {
                        switch (d.trainResult) {
                            case 0:
                                var color = "#ffa531"
                                break;
                            case 1:
                                var color = "#FFEB22"
                                break;
                            case 2:
                                var color = "#26dbee"
                                break;
                            case 3:
                                var color = "#36FFC3"
                                break;

                            default:
                                break;
                        }

                        return `<span style="color:${color}">${d.trainResultDesc}</span>`

                    },
                },
                { field: 'dataTime', title: '训练时间', align: "center" },
                {
                    title: '详情',
                    align: 'center',
                    // hide: curType == 1 || curType == 2 || curType == 6,
                    templet: function (d) {
                        let res = JSON.stringify(d);
                        return `<div class="table-tool">
                                        <div onclick='openDrawer(${res})' class="table-edit layui-btn">
                                          <img src="../static/img/icon1.png">详情
                                        </div>
                                      </div>`;
                    },
                },
            ]]
            , height: 'full'
            // ,skin: 'line' //表格风格
            , even: true
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                , groups: 3 //只显示 1 个连续页码
                , first: false //不显示首页
                , last: false //不显示尾页

            }
            , done: function (res, curr, count) {

                $('.layui-table-cell').height($('.contain-table-list').height() / 20);
            },

        });

    });
}


var curChartType = 1;
openDrawer = (res) => {

    var nodeBeginTime = res.beginTime;
    curUuid = res.trainUuid;

    if (curType == 3) {
        gunHistoryParams = {};

        layer.tab({
            area: ['90%', '80%'],
            // maxmin: true,
            // shade: 0.9,
            move: false,
            tab: [
                {
                    title: `<div  onclick=queryGunChart("${res.trainUuid}")>数据分析</div>`,
                    content: `
                    <div class="chart2-switch">
                            横坐标基准：
                            <span data-type=1 >距离</span>
                            <span data-type=2>耗时</span>
                        </div>
                         <div class="chart3-score"></div>
                    <div id="teamtrain-chart" style="width: 100%; height: calc(100% - 0.4rem); "></div>`
                },
                {
                    title: `<div  onclick=queryGunHistory()>训练明细</div>`,
                    content: $('#tab-1').html()
                }

            ],
            shadeClose: false,
            success: function (layero, index, that) {
                queryGroupPerson(res.teamId);


                // 枪炮协同切换
                $('.chart2-switch>span').click(function (e) {
                    $(e.currentTarget).addClass('active').siblings().removeClass('active');
                    curChartType = $(e.currentTarget).data().type;
                    queryGunChart()

                })

                $('.chart2-switch>span').eq(0).click()

                $('.chart3-score').empty()
                    .append(`<span>本次训练最终成绩：${res.useTime}秒 </span> 开始时间：${res.beginTime} - 结束时间：${res.endTime}`)

            }
        });


    } else {

        new AjaxChain()
            .setUrl('/train/score/detail/list')
            .setData(
                { uuid: res.trainUuid }
            )
            .then(data => {
                var str = ''
                str = data.reduce((x, y) => {
                    return x + `<div class="layui-timeline-item">
                            <i class="layui-icon layui-timeline-axis"></i>
                            <div class="layui-timeline-content layui-text">
                                <div class="layui-timeline-title">${addSeconds(nodeBeginTime, y.useTime)} → ${y.nodeName || ''}  ${(!y.useTime) ? '' : ('用时：' + y.useTime + '秒')}</div>
                            </div>
                        </div>
                `
                }, '<div class="layui-timeline">')

                str = str + '</div>'

                drawer = layer.open({
                    title: '详情',
                    type: 1,
                    area: ['30%', '80%'],
                    shade: 0.3,
                    shadeClose: false,
                    id: 'edit-offset',
                    success: function (layero, index, that) {

                    },
                    content: str
                });


            })
            .catch(err => {
                console.error('请求异常:', err);
            })
            .send();

    }

}



//枪炮协同切换弹窗tab事件
var gunHistoryParams = {}, curUuid = null;
function queryGunHistory() {


    gunHistoryParams.uuid = curUuid;
    gunHistoryParams.pageSize = 10;
    gunHistoryParams.trainType = curType;

    layui.use('table', function () {
        var table = layui.table;
        //展示已知数据
        table.render({
            elem: '#record-table'
            , text: {
                none: '暂无数据'
            }
            , method: 'get'
            , url: ajaxPrefix() + "/train/score/detail/list/page"
            , headers: {
                SessionId: JSON.parse(localStorage.getItem('sessionId'))
            }
            , where: gunHistoryParams
            , parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.result.total, //解析数据长度
                    "data": res.result.data //解析数据列表
                };
            }
            , request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                ,
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , cols: [[
                { field: 'personName', title: '姓名', align: "center" }
                , { field: 'seqNo', title: '次序', align: "center" }
                , { field: 'distance', title: '距离（米）', align: "center" }
                , { field: 'useTime', title: '用时（秒）', align: "center" }
            ]]
            , height: 'full'
            // ,skin: 'line' //表格风格
            , even: true
            , page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: ['count', 'prev', 'page', 'next', 'skip'] //自定义分页布局
                //,curr: 5 //设定初始在第 5 页
                , groups: 3 //只显示 1 个连续页码
                , first: false //不显示首页
                , last: false //不显示尾页
            }
            , done: function (res, curr, count) {
                $('.layui-table-cell').height($('.contain-table-list').height() / 20);
            },

        });

    });

}


var gunChart = null;
function queryGunChart() {
    new AjaxChain()
        .setUrl('/train/score/teamtrain/detail')
        .setData(
            { uuid: curUuid }
        )
        .then(data => {

            var persons = [
            ];
            var chartData = [['useTime', 'distance', 'personName']]


            if (curChartType == 1) {

                $.each(data, function (e, i) {
                    persons.push((i.personName + '（' + i.seqNo + '）') + ',' + i.photoPath)

                    i.uwbScoreList.forEach(element => {


                        chartData.push([element.distance, element.useTime, (i.personName + '（' + i.seqNo + '）')])

                    });
                })


            } else {

                $.each(data, function (e, i) {
                    persons.push((i.personName + '（' + i.seqNo + '）') + ',' + i.photoPath)

                    i.uwbScoreList.forEach(element => {


                        chartData.push([element.useTime, element.distance, (i.personName + '（' + i.seqNo + '）')])

                    });
                })

            }

            // chartData.sort((a, b) => a[0] - b[0]);


            const datasetWithFilters = [];
            const seriesList = [];
            echarts.util.each(persons, function (personMsg) {

                let [personName, photoPath] = personMsg.split(',')

                var datasetId = 'dataset_' + personName;
                datasetWithFilters.push({
                    id: datasetId,
                    fromDatasetId: 'dataset_raw',
                    transform: {
                        type: 'filter',
                        config: {
                            and: [
                                { dimension: 'useTime', gte: 0 },
                                { dimension: 'personName', '=': personName }
                            ]
                        }
                    }
                });
                seriesList.push({
                    type: 'line',
                    datasetId: datasetId,
                    lineStyle: {
                        shadowColor: 'rgba(0, 0, 0, 0.9)',
                        shadowBlur: 3,
                        shadowOffsetX: 3,
                        shadowOffsetY: 2,
                    },
                    showSymbol: false,
                    name: personName,
                    endLabel: {
                        show: true,
                        color: '#ddd',
                        formatter: function (params) {
                            return params.value[2] + ': ' + params.value[1] + (curChartType != 1 ? "米" : "秒");
                        }
                    },
                    labelLayout: {
                        moveOverlap: 'shiftY'
                    },
                    emphasis: {
                        focus: 'series'
                    },
                    encode: {
                        x: 'useTime',
                        y: 'distance',
                        label: ['personName', 'distance'],
                        itemName: 'useTime',
                        tooltip: ['distance']
                    }
                    // , markPoint: {
                    //     symbol: 'pin',

                    //     symbol: `image://${'/images/' + photoPath}`,
                    //     symbolSize: [40, 40],
                    //     symbolOffset: [0, -20],
                    //     label: {
                    //         show: true, // 开启显示
                    //         position: 'inside', // 在上方显示
                    //         formatter: personName,
                    //         // textStyle: { // 数值样式
                    //         //   color: '#22b8ed',
                    //         //   fontSize: 16
                    //         // },
                    //         // color: '#fff',
                    //         // backgroundColor: '#36a3f7',
                    //         // borderRadius: 4,
                    //         // padding: [4, 8]
                    //     }
                    //     ,
                    //     data: []
                    // }
                });
            });
            var option = {
                animationDuration: 10000,
                dataset: [
                    {
                        id: 'dataset_raw',
                        source: chartData
                    },
                    ...datasetWithFilters
                ],
                legend: {
                    textStyle: {
                        color: '#ddd',
                    },
                    top: '3%'
                },
                tooltip: {
                    order: 'valueDesc',
                    trigger: 'axis'
                },
                xAxis: {
                    type: 'value',
                    name: curChartType == 1 ? '行进距离（米）' : '耗时（秒）',
                    axisTick: {
                        show: false,
                    },
                    splitLine: {
                        show: false,
                        lineStyle: {
                            color: '#A8A8A822',
                        }
                    }
                },
                yAxis: {
                    name: curChartType == 1 ? '耗时（秒）' : '行进距离（米）',
                    axisTick: {
                        show: false,
                    },
                    splitLine: {
                        show: false
                    }
                },
                grid: {
                    right: "7%",
                    top: "15%",
                    left: "10%",
                    bottom: "10%"
                },
                // dataZoom: [{
                //     type: 'inside',
                //     start: chartData[1].useTime,
                //     end: chartData[chartData.length - 1].useTime
                // }, {
                //     show: true,
                //     type: 'slider',
                //     y: '90%',
                //     start: chartData[1].useTime,
                //     end: chartData[chartData.length - 1].useTime
                // }],
                series: seriesList
            };

            if (gunChart) {
                gunChart.dispose();
                gunChart = null;
            }

            gunChart = echarts.init(document.getElementById('teamtrain-chart'));

            gunChart.setOption(option);

        })
        .catch(err => {
            console.error('请求异常:', err);
        })
        .send();

}





function addSeconds(timeStr, seconds) {
    // 解析输入的时间字符串
    const [datePart, timePart] = timeStr.split(' ');
    const [year, month, day] = datePart.split('-');
    const [hours, minutes, secs] = timePart.split(':');

    // 创建 Date 对象（注意月份要减 1）
    const date = new Date(year, month - 1, day, hours, minutes, secs);

    // 添加指定秒数（转换为毫秒）
    const newTimestamp = date.getTime() + seconds * 1000;
    const newDate = new Date(newTimestamp);

    // 格式化输出
    const format = (n) => n.toString().padStart(2, '0');
    return `${newDate.getFullYear()}-${format(newDate.getMonth() + 1)}-${format(newDate.getDate())} ` +
        `${format(newDate.getHours())}:${format(newDate.getMinutes())}:${format(newDate.getSeconds())}`;
}

//回放图表
drawChart = (timeData, personData, data) => {


    var option = {
        baseOption: {
            timeline: {
                loop: false,
                // show: false,
                data: timeData,
                axisType: 'category',
                autoPlay: true,
                playInterval: 500, //播放速度
                left: '5%',
                right: '5%',
                bottom: '0%',
                width: '90%',
                //  height: null,
                label: {
                    normal: {
                        textStyle: {
                            color: '#fff',
                        },
                    },
                    emphasis: {
                        textStyle: {
                            color: 'red',
                        },
                    },
                },
                symbolSize: 10,
                lineStyle: {
                    color: '#fff',
                },
                checkpointStyle: {
                    color: 'red',
                    borderColor: '#fff',
                    borderWidth: 2,
                },
                controlStyle: {
                    show: false,
                    showNextBtn: false,
                    showPrevBtn: false,
                    normal: {
                        color: '#fff',
                        borderColor: '#ffa597',
                    },
                    emphasis: {
                        color: 'red',
                        borderColor: 'red',
                    },
                },
            },
            title: {
                text: '轨迹回放',
                right: '2%',
                bottom: '15%',
                textStyle: {
                    fontSize: 50,
                    color: 'rgba(255,255,255,.6)', //标题字体颜色
                },
            },
            tooltip: {
                show: false,
                trigger: 'axis',
            },
            calculable: true,
            grid: {
                left: '8%',
                right: '2%',
                bottom: '6%',
                top: '0%',
                containLabel: true,
            },
            label: {
                normal: {
                    textStyle: {
                        color: 'red',
                    },
                },
            },
            yAxis: [
                {
                    nameGap: 50,
                    offset: '37',
                    type: 'category',
                    interval: 50,
                    //inverse: ture,//图表倒叙或者正序排版
                    data: '',
                    nameTextStyle: {
                        color: 'red',
                    },
                    axisLabel: {
                        //rotate:45,
                        show: false,
                        textStyle: {
                            fontSize: 32,

                            color: function (params, Index) {
                                // 标签字体颜色

                                //color:function(d){return '#'+Math.floor(Math.random()*(256*256*256-1)).toString(16);//随机生成颜色

                                var colorarrays = [
                                    '#6bc0fb',
                                    '#7fec9d',
                                    '#fedd8b',
                                    '#ffa597',
                                    '#84e4dd',
                                    '#749f83',
                                    '#ca8622',
                                    '#bda29a',
                                    '#a8d8ea',
                                    '#aa96da',
                                    '#fcbad3',
                                    '#ffffd2',
                                    '#f38181',
                                    '#fce38a',
                                    '#eaffd0',
                                    '#95e1d3',
                                    '#e3fdfd',
                                    '#749f83',
                                    '#ca8622',
                                    '#fce38a',
                                ];

                                //console.log('111', Index, colorarrays[Index],params); //打印序列

                                return colorarrays[personData[0].indexOf(params)];
                            },
                        }, //rotate:45,
                        interval: 50,
                    },
                    axisLine: {
                        lineStyle: {
                            color: 'balck', //Y轴颜色
                        },
                    },
                    splitLine: {
                        show: false,
                        lineStyle: {
                            color: '#ffa597',
                        },
                    },
                },
            ],
            xAxis: [
                {
                    type: 'value',
                    name: '',

                    splitNumber: 8, //轴线个数
                    nameTextStyle: {
                        color: 'balck',
                    },
                    axisLine: {
                        lineStyle: {
                            color: '#ffa597', //X轴颜色
                        },
                    },
                    axisLabel: {
                        formatter: '{value} ',
                    },
                    splitLine: {
                        show: true,
                        lineStyle: {
                            color: '#6bcbe166',
                        },
                    },
                },
            ],
            series: [
                {
                    name: '',
                    type: 'bar',
                    markLine: {
                        label: {
                            normal: {
                                show: false,
                            },
                        },
                        lineStyle: {
                            normal: {
                                color: 'red',
                                width: 3,
                            },
                        },
                    },
                    label: {
                        normal: {
                            show: true,
                            position: 'right', //数值显示在右侧
                            formatter: '{c}米',
                            textStyle: {
                                color: '#fff',
                            }
                        },
                    },
                    itemStyle: {
                        normal: {
                            color: function (params) {
                                // build a color map as your need.
                                //color:function(d){return '#'+Math.floor(Math.random()*(256*256*256-1)).toString(16);//随机生成颜色
                                var colorList = [
                                    '#6bc0fb',
                                    '#7fec9d',
                                    '#fedd8b',
                                    '#ffa597',
                                    '#84e4dd',
                                    '#749f83',
                                    '#ca8622',
                                    '#bda29a',
                                    '#a8d8ea',
                                    '#aa96da',
                                    '#fcbad3',
                                    '#ffffd2',
                                    '#f38181',
                                    '#fce38a',
                                    '#eaffd0',
                                    '#95e1d3',
                                    '#e3fdfd',
                                    '#749f83',
                                    '#ca8622',
                                    '#fce38a',
                                ];
                                return colorList[personData[0].indexOf(params.name)] || params.color;
                            },
                        },
                    },
                },

                {
                    name: '',
                    type: 'bar',
                    markLine: {
                        label: {
                            normal: {
                                show: false,
                            },
                        },
                        lineStyle: {
                            normal: {
                                color: 'red',
                                width: 3,
                            },
                        },
                    },
                    barWidth: '50%',
                    barGap: '-100%',
                    label: {
                        normal: {
                            show: true,
                            fontSize: 16, //标签国家字体大小
                            position: 'left', //数值显示在右侧
                            formatter: function (p) {
                                return p.name;
                            },
                        },
                    },
                    itemStyle: {
                        normal: {
                            color: function (params) {
                                // build a color map as your need.
                                //color:function(d){return '#'+Math.floor(Math.random()*(256*256*256-1)).toString(16);//随机生成颜色
                                var colorList = [
                                    '#6bc0fb',
                                    '#7fec9d',
                                    '#fedd8b',
                                    '#ffa597',
                                    '#84e4dd',
                                    '#749f83',
                                    '#ca8622',
                                    '#bda29a',
                                    '#a8d8ea',
                                    '#aa96da',
                                    '#fcbad3',
                                    '#ffffd2',
                                    '#f38181',
                                    '#fce38a',
                                    '#eaffd0',
                                    '#95e1d3',
                                    '#e3fdfd',
                                    '#749f83',
                                    '#ca8622',
                                    '#fce38a',
                                ];
                                // return colorList[params.dataIndex]
                                // console.log('111', params.name); //打印序列
                                return colorList[personData[0].indexOf(params.name)];
                            },
                        },
                    },
                },
            ],

            animationEasingUpdate: 'quinticInOut',
            animationDurationUpdate: 1500, //动画效果
        },

        options: [],
    };
    for (var n = 0; n < timeData.length; n++) {
        var res = [];
        //alert(personData.length);
        for (j = 0; j < data[n].length; j++) {
            res.push({
                name: personData[n][j],
                value: data[n][j],
            });
        }

        res.sort(function (a, b) {
            return b.value - a.value;
        }).slice(0, 6);

        res.sort(function (a, b) {
            return a.value - b.value;
        });

        var res1 = [];
        var res2 = [];
        //console.log(res);
        for (t = 0; t < res.length; t++) {
            res1[t] = res[t].name;
            res2[t] = res[t].value;
        }
        option.options.push({
            title: {
                text: timeData[n] + '秒',
            },
            yAxis: {
                data: res1,
                initIndex: n
            },
            series: [
                {
                    data: res2
                },
                {
                    data: res2
                },
            ],
        });
    }
    var myChart = echarts.init(document.getElementById('teamtrain-chart'));

    myChart.setOption(option);

}


// 通过组查询成员
function queryGroupPerson(teamId) {


    new AjaxChain()
        .setUrl('/train/team/person/list')
        .setData(
            { teamId: teamId }
        )
        .then(data => {

            $('select[name="personName"]')
                .empty()
                .append(
                    data.reduce((x, y) => {
                        return x + `<option value="${y.personName}">${y.personName}</option>`
                    }, '<option value="">队员名称</option>')

                )

            form.render();

        })
        .catch(err => {
            console.error('请求异常:', err);
        })
        .send();

}


// 导出
function exportData() {

    var exportP = queryParams;
    exportP.sessionId = JSON.parse(localStorage.getItem('sessionId'))

    window.location.href = `/rest/fstation/train/score/export?${new URLSearchParams(exportP)}`;

}
